import serial


class SerialHandler:
    def __init__(self, port, baud_rate):
        self.port = port
        self.baud_rate = baud_rate
        self.serial_port = None
        self.is_open = False

    def check_connection(self):
        if not self.serial_port or not self.serial_port.is_open:
            raise serial.SerialException("串口连接断开")

    def open(self):
        try:
            self.serial_port = serial.Serial(port=self.port, baudrate=self.baud_rate, timeout=0.1)
            self.is_open = True
        except Exception as e:
            print(f"无法打开串口: {e}")
            raise e

    def close(self):
        self.serial_port.close()
        self.is_open = False

    def read_line(self):
        self.check_connection()
        if self.serial_port and self.serial_port.in_waiting > 0:
            return self.serial_port.readline().decode('utf-8', errors='ignore').strip()
        return None

    def write(self, data):
        self.check_connection()
        if self.serial_port and self.serial_port.is_open:
            self.serial_port.write(data.encode('utf-8'))
